/**
 * @file 特卖会首页<br />
 * 后三天预售品牌lazyload<br />
 * 时间标签<br />
 * 即将上线品牌的预告订阅<br />
 * 紧急广告、横幅下拉、右侧轮播、公告（异步）<br />
 * 开售预告<br />
 * 添加收藏<br />
 * 新手指引<br />
 * VIP等级提示
 * @namespace Shop.index
 * @version	1.1.1.20130117
 * @author eason<eason.chen@vipshop.com>
 */

/**
 * 最后三天预售品牌
 * 
 * @class nsBrandList
 * @memberof Shop.index
 */
var nsBrandList = {
	/**
	 * 上一次滚动的屏高，用于判断是否满足自动加载
	 * @type {Number}
	 * @default 0
	 * @memberof Shop.index.nsBrandList
	 */
	scrollTop : 0,

	/**
	 * 窗口高
	 * @type {Number}
	 * @default $(window).height()
	 * @memberof Shop.index.nsBrandList
	 */
	winHeight : $(window).height(),

	/**
	 * 品牌高，需注意与html的标签保持一致
	 * @type {Number}
	 * @default $('.s_mod:eq(0)').height()
	 * @memberof Shop.index.nsBrandList
	 */
	labHeight : $('.s_mod:eq(0)').height(),

	/**
	 * 屏内品牌数
	 * @type {Number}
	 * @default 0
	 * @memberof Shop.index.nsBrandList
	 */
	pageLab : 0,

	yesterDayFlag : false,
	
	/**
	 * @desc 初始化
	 * @method
	 * @memberof Shop.index.nsBrandList
	 */
	init : function () {
		//即将下架及即将上线的品牌为一行2个
		this.pageLab = Math.ceil(this.winHeight / this.labHeight) * 2;

		//使用事件命名空间，以便后期独立解除
		$(window)
			.on('scroll.lazyDom', this.lazyLoadDom)
			.trigger('scroll.lazyDom');
		
		//批量倒计时
		setInterval(function () {
			for (key in countDown) {
				var rt = fn_CountDown(key);

				$('.J_wrap_pro_'+ key).html(rt.day +'天'+ rt.hour +'时'+ rt.min +'分'+ rt.sec +'秒');
			}
		}, 1000);

		if (label.length <= 0 ) {
			$('#J_shopLast').hide();
		}
		if (readyLabel.length <= 0 ) {
			$('#J_shopUnsale').hide();
		}
	},

	/**
	 * @desc 随屏幕滚动而自动加载预售品牌dom内容<br /><br />
	 * <strong>这里有怪兽(⊙o⊙)</strong><br /><br />
	 * 当屏幕滚动的时候，对比当次滚动的屏高，与上次记录的高度<br />
	 * 当滚动超过2屏 + 待加载数组不为空时，开始动态插入dom节点<br /><br />
	 * 如在非页面顶部手动刷新，必须判断当前屏数，并加载相应屏数。<br />
	 * 预售图片+即将上线图片lazyload
	 * 
	 * @method
	 * @memberof Shop.index.nsBrandList
	 * @todo 记录用户最大滚屏数
	 */
	lazyLoadDom : function () {
		//总滚动屏高
		var scrollTop = $(window).scrollTop();
		//当前滚动屏高
		var scrollLimit = scrollTop - nsBrandList.scrollTop;
		
		//判断是否向下滚动超过2屏
		//补充判断是否接近lazyload起点
		if ( ( label.length > 0 || readyLabel.length > 0 )
			&& ( scrollLimit > nsBrandList.winHeight * 2
				|| (scrollTop + nsBrandList.winHeight >= nsTimeMark.yesterHeight
					&& !nsBrandList.yesterDayFlag)
				)) {
			//记录当前滚动屏高
			nsBrandList.scrollTop = scrollTop;

			if (nsBrandList.scrollTop + nsBrandList.winHeight >= nsTimeMark.yesterHeight) {
				nsBrandList.yesterDayFlag = true;
			}

			//如果从页面中部刷新页面，需要加载更多的品牌数
			//以保证滚动条还有向下滚动余量
			var scroll_lab = Math.round(scrollLimit / nsBrandList.labHeight) * 2;
			if (scroll_lab < nsBrandList.pageLab * 2) { scroll_lab = nsBrandList.pageLab; }

			//即将下架
			if (label.length > 0) {
				var app = '';
				$('#J_wrap_pro_add').Template( { templateElement:$('#J_wrap_pro_template'), replace:null } );

				while (scroll_lab > 0) {
					var lab = label.shift();
					if (typeof(lab['id']) != 'undefined') {
						app+= $('#J_wrap_pro_add').Template('process', lab);
						scroll_lab--;
					}
					else {
						break;
					}
				}
				$('#J_wrap_pro_add').append(app);
			}

			//即将上线
			if (readyLabel.length > 0 && scroll_lab > 0) {
				var app = '';
				$('#J_readyBrandList').Template( { templateElement:$('#J_wrap_ready_template'), replace:null } );

				while (scroll_lab > 0) {
					var lab = readyLabel.shift();
					if (typeof(lab['id']) != 'undefined') {
						app+= $('#J_readyBrandList').Template('process', lab);
						scroll_lab--;
					}
					else {
						break;
					}
				}
				$('#J_readyBrandList')
					.append(app)
					.find('.J_noFlash')		//开售预告不存在flash则隐藏链接
						.unwrap()
						.hide()
						.removeClass('J_noFlash');
			}

			if (typeof $.fn.lazyload == 'function') {
				$('img.lazy').lazyload({ threshold : 200 });
			}
		}

		if (label.length <= 0 && readyLabel.length <= 0) {
			//数据加载完解除事件
			$(window).off('scroll.lazyDom');
		}
	}
};


/**
 * 时间标签
 *
 * @class nsTimeMark
 * @memberof Shop.index
 */
var nsTimeMark = {
	halfTimeMark : 35,

	//每个产品窗口的高度+margin
	divHeight : $('.s_mod:eq(0)').outerHeight() + 13,

	//热销商品div高度，先定义因为可能dom未生成
	hotsellDivH : 250,

	//热销头部小标题高度
	HotTitleHeight : 36,

	//即将开售头部小标题高度
	readyTitleHeight : 36,
	hotSellHeight : 0,
	readyBrandHeight : 0,
	todayHeight : 0,
	yesterHeight : 0,

	timer : null,
	timeMarkCss : 'guid_b',
	timeDiv : $('#J_toGuide'),
	
	/**
	 * @desc 初始化时间标记
	 * @method
	 */
	init : function () {
		if (nsTimeMark.timeDiv.hasClass('hidden')) {
			nsTimeMark.timeDiv.hide();
			//ie6下不显示时间标记
			//新客不显示时间标记
			return ;
		}
		
		$(window).on('scroll.timeMark', nsTimeMark.scroll);

		//判断屏幕大小决定时间标记位置
		if($(window).width() < 1024){
			nsTimeMark.timeDiv.removeClass('guid_b').addClass('guid_c');
			nsTimeMark.timeMarkCss = 'guid_c';
		}

		this.todayHeight = newNum * this.divHeight;
		this.yesterHeight = yesterdayNum * this.divHeight + this.todayHeight;
		
		if (newNum > 0) {//10点前后的高度差
			this.todayHeight -= this.halfTimeMark;
		}
		else {
			this.yesterHeight -= this.halfTimeMark;
		}

		var row_num = 2;
		//如果新版首页（热销3列）
		if (typeof new_index != 'undefined') { row_num = 3; }
		
		//40为热销品牌的margin-top，18是热销品牌的margin-bottom
		this.hotSellHeight = this.yesterHeight + 40 + Math.ceil(hotSellNum / row_num) * this.hotsellDivH 
							+ this.HotTitleHeight;
		
		this.readyBrandHeight = this.hotSellHeight + this.readyTitleHeight - this.halfTimeMark + 
							   Math.ceil(readyBrandNum / row_num) * 254;
	},

	/**
	 * @desc 初始化时间标记
	 * @method
	 */
	scroll : function () {
		//当前滚动屏高
		var sTop = $(window).scrollTop();
		
		if (sTop > nsTimeMark.readyBrandHeight){
			//超出所有品牌时隐藏时间标记，避免遮挡底部信息
			clearTimeout(nsTimeMark.timer);
			nsTimeMark.timeDiv.fadeOut('fast');

			return ;
		}
		
		//避开banner广告没收起时时间标记的位置误差，602为用户滚到到刚好看不到时间标记的高度
		if (sTop > 602 || nsAdSense.bannerUp){
			//滚屏则相对定位
			if (nsTimeMark.timeMarkCss == 'guid_b') {
				nsTimeMark.timeDiv.removeClass('guid_b').addClass('guid_a');
			}
			else {
				nsTimeMark.timeDiv.removeClass('guid_c').addClass('guid_d');
			}
			
			//滚动时显示标记，停止时标记消失
			clearTimeout(nsTimeMark.timer);
			nsTimeMark.timeDiv.fadeIn('fast');
			nsTimeMark.timer = setTimeout(function(){
				nsTimeMark.timeDiv.fadeOut();
			}, 1000);

			//判断屏幕高度，显示提示文字
			switch (true) {
			case sTop < nsTimeMark.todayHeight:
			//今日上线
				nsTimeMark.timeDiv.html(timeStr.today);
				break;
			case sTop < nsTimeMark.yesterHeight:
			//昨日上线
				nsTimeMark.timeDiv.html(timeStr.yesterDay);
				break;
			case sTop < nsTimeMark.hotSellHeight:
			//前n日上线
				nsTimeMark.timeDiv.html(timeStr.hotSell);
				break;
			case sTop > nsTimeMark.hotSellHeight:
			//即将上线
				nsTimeMark.timeDiv.html(timeStr.coming);
				break;
			}
		}
	}
}

/**
 * 订阅模块
 * 
 * @class nsSubscribe
 * @memberof Shop.index
 */
var nsSubscribe = {
	isNotice : '',
	leftPosition : 0,
	isSubmit : false,
	checkMail : /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/,
	checkPhone : /^1[3|4|5|8][0-9]\d{4,8}$/,
	
	/**
	 * @desc 初始化
	 * @method
	 * @memberof Shop.index.nsSubscribe
	 */
	init : function () {
		//fix 浏览器的表单历史记录导致的交互问题
		$('#J_readyBrandList').delegate('.J_unsale', {
			mouseenter : function () {
				clearTimeout($(this).data('timer'));
			},
			mouseleave : function () {
				var ts = $(this);
				ts.addClass(ts.data('hover'));

				ts.data('timer', setTimeout(function (e) {
					e.removeClass(e.data('hover'));
				}, 600, ts));
			}
		});

		//触发订阅的动作
		$('input[name=email-phone]').live({
			focus : function () {
				if (nsSubscribe.isSubmit || $(this).val() == '请输入手机号码或邮箱' || $(this).val() == '') {
					$(this).val('');
				}
			},
			keydown : function () {
				$(this).parent().siblings('.J_book_warm').fadeOut('fast');
			},
			blur : function () {
				if ($(this).val() == '') {
					$(this).val('请输入手机号码或邮箱');
				}
			}
		});
		
		//订阅表单
		$('.J_book_form').live('submit', function () {
			var that = $(this);
			var input = that.find('input[name=email-phone]');
			var warm = that.find('.J_book_warm');
			var value = input.val();
			
			//区分是否为开售预告的订阅框，决定订阅弹窗位置
			nsSubscribe.isNotice = that.find('input[name=isNotice]').val();
			
			if (value == '' || value == '请输入手机号码或邮箱') {
				warm.fadeIn('fast');
				input.val('').focus();
			}
			else if (nsSubscribe.checkMail.test(value)) {
				//邮箱正确
				nsSubscribe.ajax(2, that.find('input[name=brandId]').val(), value);
			}
			else if (nsSubscribe.checkPhone.test(value) && value.length == 11) {
				//手机正确
				nsSubscribe.ajax(1, that.find('input[name=brandId]').val(), value);
			}
			else {
				warm.fadeIn('fast');
				nsSubscribe.isSubmit = true;
			}

			return false;
		});
		
		//关闭弹窗
		$('.J_pop_subscribeClose').live('click', function () {
			$('.J_subscribe_container').hide();
		});
	},
	
	/**
	 * @desc 异步提交订阅表单
	 * @method
	 * @memberof Shop.index.nsSubscribe
	 * @param {Number} type 订阅类型，1=手机，2=email
	 * @param {Number} id 品牌id
	 * @param {String|Number} val 订阅渠道，手机号或email地址
	 */
	ajax : function (type, id, val) {
		var data = {
			warehouse : wareHouse,
			brands : [id],
			businessType : 1
		};
		var typeVal = (type == 1) ? {phone : val} : {email : val};
		var visitVal = (nsSubscribe.isNotice == 'yes') ? {visitSource : 1} : {visitSource : 5};
		data = $.extend({}, data, typeVal, visitVal);
		
		$.ajax({
			url : VIPSHOP.apiHost +'/if/subscribe.php',
			data : data,
			dataType : 'jsonp',
			success : function(data){
				$('.J_subscribe_wraper').hide();
				
				var subscribeBox;
				if (nsSubscribe.isNotice == 'yes') {
					subscribeBox = $('#J_subscribe_box');
					subscribeBox.css('left', nsSubscribe.leftPosition);
				} 
				else {
					subscribeBox = $('#J_subscribe_box_' + id);
				}
				
				var callbackText = '';
				if ( data['status'] == '1' ) {
					callbackText = $('#J_subscribe_template').html().replace('{$callbackText}', subscribe_txt[0]);
             	}
             	else {
             		callbackText = $('#J_subscribe_template').html().replace('{$callbackText}', subscribe_txt[1]);
             	}
				subscribeBox
					.html(callbackText)
					.show();
			}
		});
	}
};


/**
 * 广告模块
 *
 * @class nsAdSense
 * @memberof Shop.index
 */
var nsAdSense = {
	bannerUp : false,

	/**
	 * CPS广告倒计时
	 * @type {Number}
	 * @default 0
	 * @memberof Shop.index.nsAdSense
	 */
	wheelCpsTimer : 0,

	/**
	 * 横幅广告位<br />
	 * 新客=28，旧客=6
	 * @type {Number}
	 * @default 0
	 * @memberof Shop.index.nsAdSense
	 */
	bannerID : 0,

	/**
	 * @desc 初始化
	 * @method
	 * @memberof Shop.index.nsAdSense
	 */
	init : function () {
		if (!!VIPSHOP.cookie.get('vip_new_old_user')) {
			//不一定新客
			if (!!VIPSHOP.cookie.get('VipNewUser')) {
				//新客
				this.bannerID = '28';
			}
			else {
				this.bannerID = '6';
			}
		}
		else {
			//一定新客
			this.bannerID = '28';
		}

		$.ajax ({
			url : VIPSHOP.apiHost + '/if/ad2.php',
			data : {
				act : 'getAds',
				type : '7,17,n,8,36,'+ this.bannerID,
				channelId : channelId,
				warehouse : wareHouse
			},
			jsonp : 'callback',
			jsonpCallback : 'api_ads',
			cache : true,
			dataType : 'jsonp',
			success : function (re) {
				nsAdSense
					.showBannerAds(re['AD'+ nsAdSense.bannerID])
					.showNotice(re.AD8)
					.showWheelAds(re.AD7)
					.showAnnounce(re.AD_n)
					.showTextAds(re.AD17)
					.showBeautyAd(re.AD36)
					.loadCps();
				
				//默认显示公告选项卡
				var defaultTab = re.DefaultTab ? (parseInt(re.DefaultTab, 10) - 1) : 0;
				$('#J_announce_list').Switchable({
					panelCls : '.J_announce_li',
					triggerCls : '.J_annouce_trigger',
					trigger : 'over',
					interval : 100,
					effect : 'fade',
					activeIndex : defaultTab,
					activeCls : 'selected',
					delay : 150
				});
			}
		});
	},

	/**
	 * @desc 美妆入口链接广告位
	 * @method
	 * @param {Array} data ad36
	 * @returns {Class} nsAdsense
	 */
	 showBeautyAd : function (data) {
	 	if (data.items.length > 0) {
	 		var img = new Image(), target;
	 		img.onload = function () {
	 			if (data.items[0].blank) { target = 'target="_blank"' }
		 		$('#J_beauty_ad')
		 			.html('<a href="' + data.items[0].link + '" ' + target + ' title="' + data.items[0].name + '"><img src="' + data.items[0].img + '" alt="' + data.items[0].name + '" /></a>')
		 			.addClass('beauty_ad');
	 		}
	 		img.src = data.items[0].img;
	 	}
	 	return this;
	 },

	/**
	 * @desc 紧急广告位
	 * @method
	 * @param {Array} data ad8
	 * @returns {Class} nsAdsense
	 */
	showNotice : function (data) {
		if (data.items.length > 0) {
			$('#J_wrap_adBanner').html('<img src="'+ data.items[0].img +'" alt="" width="1000" height="39" />');
		}

		return this;
	},
	
	/**
	 * @desc 下拉横幅广告
	 * @todo 最好能加载完图片后才显示广告位
	 * @method
	 * @memberof Shop.index.nsAdSense
	 * @param {Array} data 广告内容,ad6
	 * @returns {Class} nsAdSense
	 */
	showBannerAds : function (data) {
		if (data.items.length > 0) {
			var ads = '<a href="'+ data.items[0].link +'" title="'+ data.items[0].name +'"';
			if (data.items[0].blank) { ads+= ' target="_blank"' }
			ads+= '><img src="'+ data.items[0].img +'" alt="" width="1000" height="272" /></a>';

			if (nsAdSense.bannerID == '28') {
				//新客
				$('#J_wrap_adBanner')
					.html(ads)
					.delay(200)
					.show('fast')
					.delay(8000)
					.animate({ height:'39px' }, 500, function () {
						var isSetTimeTop = false;//是否已设置时间标记的高度
						nsTimeMark.timer = setTimeout(function () {
							if (nsAddFav.slideUp) {
								nsTimeMark.timeDiv.css('top', 298);
								isSetTimeTop = true;
							}
							nsTimeMark.timeDiv.fadeOut();
						}, 400);
						if (!isSetTimeTop && nsAddFav.slideUp){
							nsTimeMark.timeDiv.css('top', 298);
							isSetTimeTop = true;
						}
						nsAdSense.bannerUp = true;
					});
			}
			else {
				$('#J_wrap_adBanner')
					.html(ads)
					.delay(200)
					.show('fast')
					.delay(4000)
					.animate({ height:'39px' }, 500, function () {
						var isSetTimeTop = false;//是否已设置时间标记的高度
						nsTimeMark.timer = setTimeout(function () {
							if (nsAddFav.slideUp) {
								nsTimeMark.timeDiv.css('top', 298);
								isSetTimeTop = true;
							}
							nsTimeMark.timeDiv.fadeOut();
						}, 400);
						if (!isSetTimeTop && nsAddFav.slideUp){
							nsTimeMark.timeDiv.css('top', 298);
							isSetTimeTop = true;
						}
						nsAdSense.bannerUp = true;
					});
			}
		}
		else {
			nsAdSense.bannerUp = true;
		}

		return this;
	},
	
	/**
	 * @desc 轮播广告
	 * @todo 最好能加载完图片后才显示广告位
	 * @method
	 * @memberof Shop.index.nsAdSense
	 * @param {Array} data 广告内容,ad7
	 * @returns {Class} nsAdSense
	 */
	showWheelAds : function (data) {
		var triggerStr = '', adsStr = '', blank = '';
		for (i = 0;i < data.items.length ;i++ ) {
			if (data.items[i].blank) { blank = ' target="_blank"' }
			triggerStr += '<span class="toc"></span>';
			adsStr += '<div class="J_WheelAds"><a href="'+ data.items[i].link +'" title="'
					  + data.items[i].name +'"'+ blank +'><img src="'+ data.items[i].img +'" alt="" width="310" height="170" /></a></div>';
		}
		//手动添加cps广告位
		triggerStr += '<span class="toc"></span>';
		adsStr += '<div class="J_WheelAds"><a href="" title="" target="_blank"><img src="about:blank" alt="" width="310" height="141" /></a><div id="J_Wheel_cps" class="pic_slider_time">剩余：0天0时0分0秒</div></a></div>';

		$('#J_wrap_adRotary_trigger').append(triggerStr);
		$('#J_wrap_adRotary_cell').append(adsStr);
		
		var timer = null;
		
		//按钮渐显渐隐
		$('#J_wrap_adRotary')
			.mouseenter(function () {
				if (timer) {clearTimeout(timer);}
				$('.ahead, .next').fadeTo('fast', 0.25);
			})
			.mouseleave(function () {
				timer = setTimeout(function () {
					$('.ahead, .next').fadeTo('fast', 0);
				},500);
			})
			.Switchable({
				panelCls : '.J_WheelAds',
				triggerCls : '.toc',
				trigger : 'click',
				autoPlay : true,
				overPause : true,
				interval : 4000,
				pervCls : '.ahead',
				nextCls : '.next',
				effect : 'fade',
				activeCls : 'selected'
			});

		return this;
	},

	/**
	 * @desc 公告广告
	 * @method
	 * @memberof Shop.index.nsAdSense
	 * @param {Array} data 广告内容,ad_n
	 * @returns {Class} nsAdSense
	 */
	showAnnounce : function (data){
		var blogLi = '', fashionLi = '', cooperationLi = '';
		for (var j=0; j < data.items1.length; j++) {
			blogLi += '<li><a class="notice_link gray" target="_blank" title="'+ data['items1'][j]['title'] 
			 +'" href="'+ data['items1'][j]['link'] +'">'+ data['items1'][j]['name'] +'</a></li>';
		}
		
		for (var j=0; j < data.items2.length; j++) {
			fashionLi += '<li><a class="notice_link gray" target="_blank" title="'+ data['items2'][j]['title'] 
						+'" href="'+ data['items2'][j]['link'] +'">'+ data['items2'][j]['name'] +'</a></li>';
		}
		
		for (var j=0; j < data.items3.length; j++) {
			cooperationLi += '<li><a class="notice_link gray" target="_blank" title="'+ data['items3'][j]['title'] 
							+'" href="'+ data['items3'][j]['link'] +'">'+ data['items3'][j]['name'] +'</a></li>';
		}
		$('.J_announce_li:eq(0)').prepend(blogLi);
		$('.J_announce_li:eq(1)').prepend(fashionLi);
		$('.J_announce_li:eq(2)').prepend(cooperationLi);

		return this;
	},
	
	/** 
	 * @desc 文字广告
	 * @method
	 * @memberof Shop.index.nsAdSense
	 * @param {Array} data 广告内容,ad17
	 * @returns {Class} nsAdSense
	 */
	showTextAds : function (data) {
		var textAdsStr = '';

		if (data.items.length > 0) {
			for (var i = 0; i < data.items.length; i++) {
				var blank = data.items[i].blank ? '_blank' : '_self';
				textAdsStr += '<p class="J_textAd"><img class="text_ad_icon" src="'+ data.items[i].img 
							 +'" /><a class="text_ad_text" target="'+ blank +'" href="'+ data.items[i].link 
							 +'">'+ data.items[i].name +'</a></p>';
			}
			$('#J_textAd_frame').append(textAdsStr);
		}
		else {
			$('#J_textAd_frame').addClass('hidden');
		}
		
		//文字广告的轮播功能，如果数据多于两条则开始滚动
		if (data.items.length > 1) {
			$('#J_textAd_frame').Switchable({
				panelCls : '.J_textAd',
				autoPlay : true,
				overPause : true,
				interval : 2000,
				effect : 'slide'
			});
		}

		return this;
	},

	/**
	 * @desc cps广告
	 * 必须在轮播广告完成后才插入，保证在最后一位
	 * @method
	 * @memberof Shop.index.nsAdSense
	 * @returns {Class} nsAdSense
	 */
	loadCps : function () {
		$.ajax ({
			url : 'http://u.vipshop.com/cps.php',
			data : {
				warehouse : wareHouse
			},
			jsonp : 'callback',
			jsonpCallback : 'api_cps',
			cache : true,
			success : function (re) {
				if (re.ad_src) {
					$('.J_WheelAds:last')
						.find('a').attr('href', re.ad_link).end()
						.find('img').attr('src', re.ad_src);

					nsAdSense.wheelCpsTimer = re.end_time;

					setInterval(function () {
						rt = fn_CountDown(nsAdSense.wheelCpsTimer);
						$('#J_Wheel_cps').html('剩余：'+ rt.day +'天'+ rt.hour +'时'+ rt.min +'分'+ rt.sec +'秒');
					}, 1000);
				}
			},
			dataType : 'jsonp'
		});

		return this;
	}
};


/**
 * 开售预告
 *
 * @class nsSalePlan
 * @memberof Shop.index
 */
var nsSalePlan = {
	/**
	 * 开售品牌本地缓存
	 * @example
	 {
	 	'20120901' : {
			'date' : '20120901',
			'items' : [
				{ 'id' : 111, 'logo' : ... }
				...
			]
	 	},
	 	'20120902' : {
			...
	 	}
	 }
	 * @type {Object}
	 * @default {}
	 * @memberof Shop.index.nsSalePlan
	 */
	data : {},
	timeout : null,

	/**
	 * @desc 初始化
	 * @method
	 * @memberof Shop.index.nsSalePlan
	 */
	init : function () {
		//预售栏交互
		$('#J_wrap_salePlan')
			.delegate('.J_brandLogo', {
				mouseenter : nsSalePlan.show,
				mouseleave : nsSalePlan.hide
			})
			.delegate('#J_book_frame', {
				mouseenter : function () {
					clearTimeout(nsSalePlan.timeout);

					$(this).fadeIn('fast');
				},
				mouseleave : nsSalePlan.hide
			})
			.Switchable({
				panelCls : '.J_comingBrand',
				triggerCls : '.J_comingBrand_btn',
				trigger : 'over',
				interval : 1000,
				activeCls : 'selected',
				delay : 200
			});
	},

	/**
	 * @desc 页面回调函数异步请求某天预售品牌数据
	 * @method
	 * @memberof Shop.index.nsSalePlan
	 * @param {Number} date 日期时间
	 */
	showSalePlan : function (date) {
		$.getJSON('/index-ajax.php?act=getDayBrandList&warehouse='+ wareHouse +'&date=' + date, function (data) {
			$('#J_wrap_salePlan_' + data.date)
				.Template( { templateElement:$('#J_wrap_salePlan_template'), replace:true } )
				.Template('process', data);
			nsSalePlan['data'][data.date] = data;
		});
	},

	/**
	 * @desc 隐藏订阅窗口
	 * @method
	 * @memberof Shop.index.nsSalePlan
	 */
	hide : function () {
		clearTimeout(nsSalePlan.timeout);

		nsSalePlan.timeout = setTimeout(function () {
			$('#J_book_frame').fadeOut();
		}, 400);
	},

	/**
	 * @desc 显示订阅窗口
	 * @method
	 * @memberof Shop.index.nsSalePlan
	 */
	show : function () {
		clearTimeout(nsSalePlan.timeout);
		
		var ts = $(this);
		//返回开售品牌的日期
		var tmp = ts.parents('.J_comingBrand').attr('id').split('_');
		var date = tmp[3];
		var hoverIndex = ts.index();

		if (nsSalePlan['data'][date]) {
			$('#J_book_frame')
				.Template( { templateElement:$('#J_book_template'), replace:true } )
				.Template('process', nsSalePlan['data'][date]['items'][hoverIndex]);
		}
		if (!nsSalePlan['data'][date]['items'][hoverIndex]['flash']) {
			//开售预告不存在flash则隐藏链接
			$('.J_if_flash')
				.unwrap()
				.addClass('hidden');
		}

		//根据触发事件的logo的下标判断logo所在列数
		var leftVal;
		switch (hoverIndex % 3) {
			case 0 :
				leftVal = -331;
				break;
			case 1 :
				leftVal = -230;
				break;
			default:
				leftVal = -130;
		}
		nsSubscribe.leftPosition = leftVal - 35;
		
		//设定弹出框的位置
		var frameDivH = 300;//弹窗高度
		var logoDivH = 50;//logo框高度
		var allLogoRow = Math.ceil(nsSalePlan['data'][date]['items'].length / 3);
		var topMultiple = Math.ceil(hoverIndex / 3);
		var topPosition;

		if (topMultiple < 4) {
			topPosition = 0;
		}
		else if (allLogoRow - topMultiple > 3) {
			topPosition = (topMultiple-1) * logoDivH;
		} 
		else {
			topPosition = allLogoRow * logoDivH - frameDivH;
		}
		nsSubscribe.leftPosition = leftVal - 35;
		
		$('#J_book_frame').css({
			left : leftVal,
			top : topPosition
		});
		nsSalePlan.timeout = setTimeout(function () {
			$('#J_book_frame').fadeIn();
		}, 400);
	}
};


/**
 * 添加收藏
 *
 * @class nsAddFav
 * @memberof Shop.index
 */
var nsAddFav = {
	slideUp : false,

	/**
	 * @desc 初始化
	 * @method
	 * @memberof Shop.index.nsAddFav
	 */
	init : function () {
		var strCookie = VIPSHOP.cookie.get('te_add_favorite');

		if (!strCookie) {
			//打开收藏栏
			$('#J_favorite').slideDown();

			//点击收藏按钮
			$('.J_favorite_add,#J_favorite_add,.add_favorite_words').on('click', function () {
			    var fav_url = window.location.href +'?cmpid=20120719-ch-sc-xm';
				var fav_title = '唯品会Vipshop名牌时尚折扣网';

				if (document.all && window.external) {
					window.external.AddFavorite(fav_url,fav_title);
					nsAddFav.setCookie(1);
				} 
				else if (window.sidebar) {
					if (window.navigator.userAgent.indexOf('Chrome') !== -1) {
						alert('浏览器不支持，请使用Ctrl+D进行手动添加');
						nsAddFav.setCookie(1);
					} 
					else {
						window.sidebar.addPanel(fav_title,fav_url, '');
						nsAddFav.setCookie(1);
					}
				} 
				else {
					alert('浏览器不支持，请使用Ctrl+D进行添加');
					nsAddFav.setCookie(1);
				}

				$('#J_favorite').slideUp('400', nsAddFav.closeBar);
			});
            
            //关闭收藏
			$('#J_favorite_close').on('click', function (){
				$('#J_favorite').slideUp('400', nsAddFav.closeBar);
				nsAddFav.setCookie(0);
			});
		}
		else {
			nsAddFav.closeBar();
		}
	},

	/**
	 * @desc 调整时间标记的位置
	 * @method
	 * @memberof Shop.index.nsAddFav
	 */
	closeBar : function () {
		nsAddFav.slideUp = true;

		if (nsAdSense.bannerUp) { nsTimeMark.timeDiv.css('top', 298); }
	},

	/**
	 * @desc 保存cookie
	 * @method
	 * @memberof Shop.index.nsAddFav
	 * @param {Number} type 保存类型，1=收藏，0=关闭
	 */
	setCookie : function (type) {
		if (type == 1) {
			//点击收藏
			VIPSHOP.cookie.set('te_add_favorite', '1', false, false, 87600);
		}
		else {
			//点击关闭
			VIPSHOP.cookie.set('te_add_favorite', '0', false, false, 720);
		}
	}
};


/**
 * 新手指引
 *
 * @class nsFirstVisit
 * @memberof Shop.index
 */
var nsFirstVisit = {
	init : function() {
		if (!VIPSHOP.cookie.get('vip_new_old_user')) {
			nsFirstVisit.showTips();
		}
	},

	showTips : function() {
		var winHeight = $(window).height();
		var guideWidth = ($(window).width() - $('#firstTips').width()) / 2;
		var guideHeight = ($(window).height() - $('#firstTips').height()) / 2;
		$("html").css('overflow','hidden');

		//全屏新手指引
		$('#J_index_mask')
			.css({'height':winHeight + 'px'})
			.show();
			
		$('#firstTips')
			.css({'left':guideWidth + 'px',"top":guideHeight +"px"})
			.show();
		$(".next_w").click(function () {
		$(".tips1").hide();
		$(".tips2").show();
	});

	$(".pre_w").click(function () {
		$(".tips2").hide();
		$(".tips1").show();
	});
        $('.tips_close,.now_go').on('click', nsFirstVisit.hiddenTips);
		$(window).on("resize.FirstVisit", nsFirstVisit.showTips);
	},

	hiddenTips : function() {
		$("html").css('overflow','auto');
		$('#firstTips,#J_index_mask')
			.fadeOut('fast', function () {$(this).remove();});
		$(window).off("resize.FirstVisit");

		//新品开售指引
		$('#J_day_guide')
			.show()
			.find('span')
				.on('click',function(){
					$('#J_day_guide')
						.fadeOut('fast', function () {$(this).remove();});
				});
	}
};

/*-vip等级弹窗-*/
var popviptip = '';

function getVipGrade(){
    var VTlevel;
    var requestHash =window.location.hash;
    if (!requestHash) return false;
    var vipGradePosition=requestHash.lastIndexOf('#V');
    if (vipGradePosition < 0) return false;
    if (requestHash.length < vipGradePosition+2) return false;
    VTlevel = parseInt(requestHash.substr(vipGradePosition+2));
    location.hash=requestHash.substr(0, vipGradePosition);
    return 	VTlevel;	
}
function closs_viptip () { popviptip.close(); }

jQuery(document).ready(function(e) {
	var VTlevel = getVipGrade();
	if (VTlevel) {
		var level_name;
		if(VTlevel==2){level_name='白金'}
		else{level_name=''}
		popviptip=new $.Dialog({
			size:[380,60],
			position:[],
			model:true,
			content:'<p>了解更多特权请查看<a href=\'http://www.vipshop.com/help_center/help_art.php?act=detail&id=110\' target=\'_blank\' class=\'pink\'>帮助中心-会员特权计划</a><br>马上开启您的购物特权之旅吧！</p><em class=\'close_btn user_vip\' onclick=\'closs_viptip()\'></em>',
			elStyle : 'pop_viptip',
			 title:'<strong>恭喜您升级为'+level_name+'VIP会员（<em class=\'pink\'>V'+VTlevel+'</em>）</strong>',
			 button:[
				['button', '确定', closs_viptip]
			],
			effect : {
				effect : 'slide',
				duration : 200
			},
			zIndex:100,
			showEvent : function () {}
		})
		popviptip.open();	
	}
});

$(function () {
	nsTimeMark.init();
	nsBrandList.init();
	nsSalePlan.init();
	nsSubscribe.init();
	nsAdSense.init();
	nsAddFav.init();
	nsFirstVisit.init();

	if (!VIPSHOP.cookie.get('vip_new_old_user')) {
		var today = new Date();
		var time_str = today.getMonth()+1+' '+today.getDate()+','+today.getFullYear();
		var get_over_time = new Date(time_str);

		//准时第二天10点失效
		today.setTime(get_over_time.getTime()+34*60*60*1000);	
	    document.cookie = 'VipNewUser=1;expires='+ today.toGMTString() +';domain=vipshop.com;path=/';
		VIPSHOP.cookie.set('vip_new_old_user', '1', '.vipshop.com', '/', 8760);
	}

	//当前子频道
	$('.nav_sub_list>li:eq('+ channelId +')>a').addClass('cur');

  // 是否显示问卷调查入口
  if (VIPSHOP.cookie.get('vip_new_old_user') &&
    VIPSHOP.cookie.get('VipNewUser') && !VIPSHOP.cookie.get('have_ques')) {
    $('#J_question').show();
  }
});
